package com.csxy.six.util;

import com.csxy.six.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Component
public class SecurityUtil {

    private static JwtUtils jwtUtils;

    @Autowired
    public void setJwtUtils(JwtUtils jwtUtils) {
        SecurityUtil.jwtUtils = jwtUtils;
    }

    public static Long getCurrentUserId() {
        // 从请求头中获取JWT令牌
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }

        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                // 解析JWT令牌
                Claims claims = jwtUtils.parseToken(token);
                return Long.parseLong(claims.getSubject());
            } catch (Exception e) {
                // 令牌无效
                return null;
            }
        }
        return null;
    }
}